package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"gitee.com/czy233/go-ceph/rados"
)

type Object struct {
	Obj_id  string `json:"obj"`
	Content []byte `json:"content"`
}

func (s *Ceph) ReadFromCeph(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	oid := r.FormValue("oid")
	offset, err := strconv.ParseUint(r.FormValue("off"), 10, 64)
	if err != nil {
		fmt.Println("parse offset to uint error")
		return
	}
	length, err := strconv.Atoi(r.FormValue("len"))
	if err != nil {
		fmt.Println("parse length to int error")
		return
	}

	var data []byte
	data = make([]byte, length)
	ret, err := s.ioctx.Read(oid, data, offset)
	if err != nil {
		fmt.Println("error when read obj:", err)
		return
	}
	data = data[0:ret]
	send_len, _ := w.Write(data)
	fmt.Printf("read obj: %s, ret: %d, send data length: %d\n", oid, ret, send_len)

}

func (s *Ceph) WriteToCeph(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	var obj Object
	err := json.NewDecoder(r.Body).Decode(&obj)
	if err != nil {
		return
	}

	err = s.ioctx.WriteFullWithPutHash(obj.Obj_id, obj.Content)
	if err != nil {
		fmt.Println("error when read obj:", err)
		return
	}
	fmt.Printf("write obj: %s, length: %d\n", obj.Obj_id, len(obj.Content))
	_, _ = w.Write([]byte(strconv.Itoa(len(obj.Content))))
}

func InitsServer() {
	conn, err := rados.NewConn()
	if err != nil {
		fmt.Println("error when invoke a new connection:", err)
		return
	}
	defer conn.Shutdown()

	err = conn.ReadConfigFile("/etc/ceph/ceph.conf")
	if err != nil {
		fmt.Println("error when read default config file:", err)
		return
	}

	err = conn.Connect()
	if err != nil {
		fmt.Println("error when connect:", err)
		return
	}

	fmt.Println("connect ceph cluster ok!")

	ioctx, err := conn.OpenIOContext("testbench")
	if err != nil {
		fmt.Println("error when open IO context:", err)
		return
	}
	ceph := &Ceph{
		ioctx: ioctx,
	}

	http.HandleFunc("/get", ceph.ReadFromCeph)
	http.HandleFunc("/put", ceph.WriteToCeph)

	http.ListenAndServe(":8080", nil)
	fmt.Println("service start ...")
}
